#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

int my_recvfrom(int sockfd,char* buf,int length,struct sockaddr* client_addr,socklen_t* client_addrlen){

    int temp=0;
    int ftemp=0;

    while(1){
        
        ftemp=recvfrom(sockfd,buf+temp,length - temp,0,client_addr,client_addrlen);//0 阻塞(发送的缓冲区满/网络阻塞);
        if(ftemp == -1){
            perror("my_recv err");
            return -1;
        }if(ftemp == 0){
            return 0;
        }
        temp+=ftemp;
        if(temp >= length){
            break;
        }
        
    }
    return temp;
}


int main(void){
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);//ipv4,tcp
    if(sockfd == -1){
        perror("sock err");
        return -1;
    }
    //服务器地址:IP 端口号
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port =htons(8888);
    
    addr.sin_addr.s_addr=INADDR_ANY;//本地的ip都可以
    printf("IP=%s\n",inet_ntoa(addr.sin_addr));
    socklen_t addrlen= sizeof(addr);
    //绑定
    if(bind(sockfd,(struct sockaddr*)&addr,addrlen) == -1){
        perror("bind err");
        close(sockfd);
        return -1;
    }
    //收发数据
    char buf[64]={0};
    int ret=0;
    struct sockaddr_in client_addr;
    socklen_t client_addrlen=0;
    while(1){
        ret =my_recvfrom(sockfd,buf,sizeof(buf),(struct sockaddr*)&client_addr,&client_addrlen);
        if(ret < 0){
            perror("recvfrom err");
            continue;
        }else if(ret > 0){
            if(strcmp(buf,"quit") == 0){
                printf("client quit\n");
                break;
            }
            printf("recvfrom data:%s\n",buf);
        }else{
            printf("perr quit\n");
            break;
        }
    }

    close(sockfd);


    return 0;
}
